package com.example.controller;

import com.example.dao.ScoreCrudRepository;
import com.example.dao.TestPaperCrudRepository;
import com.example.dao.UserCrudRepository;
import com.example.pojo.*;
import com.example.pojo.vo.TestPaperForTestVo;
import com.example.tools.JwtUtils;
import com.example.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/testPaper")
@Slf4j
public class TestPaperController {
    @Autowired
    private TestPaperCrudRepository testPaperCrudRepository;
    @Autowired
    private UserCrudRepository userCrudRepository;
    @Autowired
    private ScoreCrudRepository scoreCrudRepository;

    @PostMapping("/addTestPaper")
    public Result add(@RequestBody TestPaper testPaper) {
        TestPaper save = testPaperCrudRepository.save(testPaper);
        return Result.success(save);
    }

    //为计划配置试题
    @PostMapping("/chooseQuestions")
    @Transactional
    public Result chooseQuestions(@RequestBody List<Integer> ids, @RequestParam Integer trainingPlanId) {
        for (Integer questionId : ids) {
            TestPaper testPaper = new TestPaper(null, trainingPlanId, questionId, 5D);
            testPaperCrudRepository.save(testPaper);
        }
        return Result.success();
    }

    //为计划取消配置试题
    @PostMapping("/unchooseQuestions")
    @Transactional
    public Result unchooseQuestions(@RequestBody List<Integer> ids, @RequestParam Integer trainingPlanId) {

        for (Integer questionId : ids) {
            testPaperCrudRepository.deleteByTestQuestionIdAndTrainingPlanId(questionId, trainingPlanId);
        }
        return Result.success();
    }

    @PostMapping("/updateScore")
    public Result updateScore(@RequestParam Integer trainingPlanId, @RequestParam Integer testQuestionId, @RequestParam Double score) {
        TestPaper testPaper = testPaperCrudRepository.getTestPaperByTrainingPlanIdAndTestQuestionId(trainingPlanId, testQuestionId);
        testPaper.setScore(score);
        // 保存更改
        testPaperCrudRepository.save(testPaper);
        return Result.success();
    }
    @GetMapping("/getScore")
    public Result getScore(@RequestParam Integer trainingPlanId, @RequestParam Integer testQuestionId) {
        TestPaper testPaper = testPaperCrudRepository.getTestPaperByTrainingPlanIdAndTestQuestionId(trainingPlanId, testQuestionId);

        return Result.success(testPaper.getScore());
    }

    //考试专用
    @GetMapping("/selectedQuestionAndScore")
    public Result selectedQuestionAndScore(@RequestParam Integer trainingPlanId,@RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        Score myscore = scoreCrudRepository.getScoreByTrainingPlanIdAndUserId(trainingPlanId, user.getId());
        if(myscore!=null){
            //已有成绩
            return Result.error("你已完成考试,分数为："+myscore.getScore());
        }
        List<TestPaperForTestVo> testPaperForTestVos = testPaperCrudRepository.selectedQuestionAndScore(trainingPlanId);

        log.info("selectedQuestionAndScore,{}",testPaperForTestVos);
        return Result.success(testPaperForTestVos);
    }



    @DeleteMapping("/deleteTestPaper")
    public Result delete(@RequestBody List<Integer> ids) {

        for (Integer id : ids) {
            testPaperCrudRepository.deleteById(id);
        }
        return Result.success("删除成功");
    }

    @PostMapping("/updateTestPaper")
    public Result update(@RequestBody TestPaper testPaper) {
        TestPaper save = testPaperCrudRepository.save(testPaper);
        return Result.success(save);
    }

    @PostMapping("/getAllTestPaper")
    public Result getAllTestPaper(@RequestBody TestPaper testPaper,
                                  @RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("TestPaper:{}", testPaper);
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.Direction.ASC, "id");

        Page<TestPaper> coursePage = testPaperCrudRepository.findAll(new Specification<TestPaper>() {
            @Override
            public Predicate toPredicate(Root<TestPaper> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //获取条件对象
                Predicate predicate = cb.conjunction();
                //判断用户对象
                if (testPaper != null) {
                    // 根据 student 的属性添加查询条件
                    if (testPaper.getId() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("id"), testPaper.getId()));
                    }
                }
                return predicate;
            }
        }, pageable);
        List<TestPaper> TestPapers = coursePage.getContent();
        long elements = coursePage.getTotalElements();
        return Result.success(new PageBean(elements, TestPapers));
    }

    @GetMapping("/getTestPaperList")
    public Result getTestPaperList() {
        Iterable<TestPaper> all = testPaperCrudRepository.findAll();
        List<TestPaper> testPaperList = new ArrayList<>();
        for (TestPaper testPaper : all) {
            testPaperList.add(testPaper);
        }
        return Result.success(testPaperList);
    }

    @GetMapping("/getTestQuestion")
    public Result getTestQuestion(Integer trainingPlanId, Integer choose, @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        List<TestQuestion> testQuestion = new ArrayList<>();
        if (choose == 0) {
            testQuestion.addAll(testPaperCrudRepository.unselectedQuestion(trainingPlanId, user.getAgencyId()));
        } else {
            testQuestion.addAll(testPaperCrudRepository.selectedQuestion(trainingPlanId));
        }
        return Result.success(testQuestion);
    }

    //考试获取试题
    @GetMapping("/getTestQuestionListForTest")
    public Result getTestQuestionListForTest(Integer trainingPlanId, @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        List<TestQuestion> testQuestion = testPaperCrudRepository.selectedQuestion(trainingPlanId);
        return Result.success(testQuestion);
    }


}
